<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>TP2 SIG</title>
    <style>
        html, body {
            height: 100%;
            margin: 0;
            padding: 0;
            font-family: arial,sans-serif;
            background-image: url(http://brandthunder.com/wp/wp-content/uploads/2011/11/Mac_Desktop_Background.jpg);
        }

        #map-canvas, #map_canvas {
            height: 100%;
        }

        #panel {
            position: absolute;
            top: 5px;
            left: 50%;
            margin-left: -180px;
            z-index: 5;
            background-color: #fff;
            padding: 5px;
            border: 1px solid red;
        }

        ol, ul, li {
            margin: 0;
            padding: 0;
        }

        /*?  start styles for the ContextMenu?  */
        .context_menu {
            background-color: white;
            border: 1px solid #4178B1;
            margin: 3px;
        }

        .context_menu_item {
            padding: 3px 6px;
        }

            .context_menu_item:hover {
                background-color: #CCCCCC;
            }

        .context_menu_separator {
            background-color: gray;
            height: 1px;
            margin: 0;
            padding: 0;
        }

        #transportBy, #way {
            margin: 10px;
        }

        #transportBy input:hover , #way input:hover {
            cursor:pointer
        }

        #waypoints li input {
            border-radius: 7px;
        }

        li a:hover {
            cursor: pointer;
        }

        .buttons input {
            border-radius:7px;
            height: 28px;
        }

        .buttons input:hover {
            cursor: pointer;
        }

        #waypoints li a {
            color:#BA0000 ; font-weight:bold
        }


        /*?  end styles for the ContextMenu?  */
    </style>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
    <script src="http://code.martinpearman.co.uk/googlemapsapi/contextmenu/1.0/src/ContextMenu.js"></script>
    <script>
        var directionsDisplay;
        var directionsService = new google.maps.DirectionsService();
        var map;

        function initialize() {
            directionsDisplay = new google.maps.DirectionsRenderer();
            var bsas = new google.maps.LatLng(-34.5, -58.5);
            var mapOptions = {
                zoom: 6,
                mapTypeId: google.maps.MapTypeId.ROADMAP,
                center: bsas
            }
            map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
            directionsDisplay.setMap(map);

            //?  create the ContextMenuOptions object
            var contextMenuOptions = {};
            contextMenuOptions.classNames = { menu: 'context_menu', menuSeparator: 'context_menu_separator' };

            //?  create an array of ContextMenuItem objects
            var menuItems = [];
            menuItems.push({ className: 'context_menu_item', eventName: 'directions_from', label: 'Ruta desde aqu&iacute;' });
            menuItems.push({ className: 'context_menu_item', eventName: 'directions_to', label: 'Ruta hacia aqu&iacute;' });
            menuItems.push({ className: 'context_menu_item', eventName: 'directions_add', label: 'Agregar destino' });
            menuItems.push({});
            menuItems.push({ className: 'context_menu_item', eventName: 'zoom_in_click', label: 'Zoom in' });
            menuItems.push({ className: 'context_menu_item', eventName: 'zoom_out_click', label: 'Zoom out' });
            //?  a menuItem with no properties will be rendered as a separator
            menuItems.push({});
            menuItems.push({ className: 'context_menu_item', eventName: 'center_map_click', label: 'Center map here' });
            contextMenuOptions.menuItems = menuItems;

            //?  create the ContextMenu object
            var contextMenu = new ContextMenu(map, contextMenuOptions);

            //?  display the ContextMenu on a Map right click
            google.maps.event.addListener(map, 'rightclick', function (mouseEvent) {
                contextMenu.show(mouseEvent.latLng);
            });

            //?  listen for the ContextMenu 'menu_item_selected' event
            google.maps.event.addListener(contextMenu, 'menu_item_selected', function (latLng, eventName) {
                //?  latLng is the position of the ContextMenu
                //?  eventName is the eventName defined for the clicked ContextMenuItem in the ContextMenuOptions
                switch (eventName) {
                    case 'directions_from':
                        var li = $("#waypoints li").first();
                        fillDescription(latLng, li.find("input"));
                        break;
                    case 'directions_to':
                        var li = $("#waypoints li").last();
                        fillDescription(latLng, li.find("input"));
                        break;
                    case 'directions_add':
                        var li = addWaypoint();
                        fillDescription(latLng, li.find("input"));
                        break;
                    case 'zoom_in_click':
                        map.setZoom(map.getZoom() + 1);
                        map.panTo(latLng);
                        break;
                    case 'zoom_out_click':
                        map.setZoom(map.getZoom() - 1);
                        map.panTo(latLng);
                        break;
                    case 'center_map_click':
                        map.panTo(latLng);
                        break;
                }
            });
        }

        function fillDescription(latLng, input) {
            var geocoder = new google.maps.Geocoder();
            geocoder.geocode({ latLng: latLng }, function (results, status) {
                input.val(results[0].formatted_address);
            })
        }

        function calcRoute() {
            var selectedMode = getRadioValue('mode');
            var optimizeValue = new Boolean(parseInt(getRadioValue('optimize')));
            var waypts = getWayptsArray();
            var start = waypts[0];
            var end = waypts[waypts.length - 1];

            var request = {
                origin: start.location,
                destination: end.location,
                waypoints: waypts.slice(1, waypts.length - 1),
                optimizeWaypoints: optimizeValue.valueOf(),
                travelMode: google.maps.TravelMode[selectedMode],
                unitSystem: google.maps.UnitSystem.METRIC
            };
            directionsService.route(request, function (response, status) {
                if (status == google.maps.DirectionsStatus.OK) {
                    directionsDisplay.setDirections(response);
                    var route = response.routes[0];
                    var summaryPanel = document.getElementById('directions_panel');
                    summaryPanel.innerHTML = '';
                    // For each route, display summary information.
                    for (var i = 0; i < route.legs.length; i++) {
                        var routeSegment = i + 1;
                        summaryPanel.innerHTML += '<b>Tramo: ' + routeSegment + '</b><br>';
                        summaryPanel.innerHTML += route.legs[i].start_address + ' hasta ';
                        summaryPanel.innerHTML += route.legs[i].end_address + '<br>';
                        summaryPanel.innerHTML += route.legs[i].distance.text + '<br><br>';
                    }

                    summaryPanel.innerHTML += '<p><b>Distancia total: ' + round(computeTotalDistance(response), 1) + ' km</b></p>';
                }
            });
        }

        function getRadioValue(radiosName) {
            var radios = document.getElementsByName(radiosName);
            var checked;
            for (var i = 0; i < radios.length; i++) {
                if (radios[i].checked) {
                    checked = radios[i].value;
                }
            }
            return checked;
        }

        function computeTotalDistance(result) {
            var total = 0;
            var myroute = result.routes[0];
            for (var i = 0; i < myroute.legs.length; i++) {
                total += round(myroute.legs[i].distance.value, 1);
            }
            total = total / 1000;
            return total;
        }

        function addWaypoint() {
            var waypoints = $("#waypoints");
            if (waypoints.children().length >= 8) {
                alert("La API de Google no permite utilizar m\u00E1s de 8 Waypoints.");
                return;
            }

            var li = $("#waypoint-template").children().clone();
            waypoints.append(li);
            showRemovers();
            return li;
        }

        function getWayptsArray() {
            var valid = true;
            var waypoints = [];
            $("#waypoints input").each(function () {
                var input = $(this);
                if (input.val() == "") {
                    alert("Debe completar todos los destinos");
                    valid = false;
                    return false;
                }
                waypoints.push({ location: input.val(), stopover: true });
            });
            return valid ? waypoints : null;
        }

        function removeWaypoint(anchor) {
            var li = $(anchor).parent();
            li.remove();
            showRemovers();
        }

        function showRemovers() {
            var li = $("#waypoints li");
            if (li.length > 2) {
                $("a", li).show();
            } else {
                $("a", li).hide();
            }
        }

        function round(number, digits) {
            var original = parseFloat(number);
            var a = Math.pow(10, digits);
            return Math.round(original * a) / a;
        }

        function cleanAll() {
            $("#waypoints").empty();
            addWaypoint();
            addWaypoint();
            directionsDisplay.setDirections({ routes: [] });
        }

        google.maps.event.addDomListener(window, 'load', initialize);
    </script>
</head>
<body>
    <div id="map-canvas" style="float: left; width: 70%; height: 100%;"></div>
    <div id="control_panel" style="float: right; width: 30%; text-align: left; padding-top: 20px">
        <div id="transportBy">
            <h3>Medio de transporte</h3>
            <input type="radio" name="mode" value="DRIVING" checked="checked" />Auto
            <input type="radio" name="mode" value="WALKING" />A pie
        </div>
        <div id="way">
            <h3>Camino &oacute;ptimo</h3>
            <input type="radio" name="optimize" value="1" checked="checked" />Si
            <input type="radio" name="optimize" value="0" />No 
        </div>
        <div style="border-bottom:1px solid #4178B1; margin-top:30px"></div>
        <div style="margin: 40px; border-width: 2px;">
            <ol id="waypoints" type="A">
                <li>
                    <input type="text" /><a onclick="removeWaypoint(this);" style="display: none;">x</a></li>
                <li>
                    <input type="text" /><a onclick="removeWaypoint(this);" style="display: none;">x</a></li>
            </ol>
            <div class="buttons" style="margin-top:20px; display:block">
                <input type="button" value="Agregar destino" onclick="addWaypoint();" />
                <input type="button" value="C&oacute;mo llegar" onclick="calcRoute();">
                <input type="button" value="Limpiar" onclick="cleanAll();">
            </div>
        </div>
        <div id="templates" style="display: none;">
            <div id="waypoint-template">
                <li>
                    <input type="text" /><a onclick="removeWaypoint(this)">x</a>
                </li>
            </div>
        </div>
        <div id="directions_panel" style="margin: 20px; background-color: #FFEE77;"></div>
    </div>
</body>
</html>
